package cn.edu.zafu.bigdata.hzq;

import java.io.*;
import java.util.Scanner;

public class FileAppendOperations {

    // 追加内容到文件
    public static void appendToFile(String fileName, String content) {
        try (FileWriter fw = new FileWriter(fileName, true);
             BufferedWriter bw = new BufferedWriter(fw);
             PrintWriter out = new PrintWriter(bw)) {
            out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取文件内容
    public static void readFile(String fileName) {
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 主方法，用于测试
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要追加到文件的文本：");
        String inputText = scanner.nextLine();
        String fileName = "example.txt"; // 假设文件名为example.txt

        // 追加文本到文件
        appendToFile(fileName, inputText);

        // 读取并显示文件内容
        readFile(fileName);

        scanner.close();
    }
}